<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Chat</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='chat_style.css') }}">
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intro.js/5.1.0/introjs.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intro.js/5.1.0/intro.min.js"></script>
</head>

<body>
    <div class="chat-container">

        <div class="friend-list">
            <div class="container">

                <div class="user-avatar-container">

                    <div class="current-user-avatar">
                        <img src="{{ url_for('static', filename=current_user_avatar_path) }}"
                            alt="{{ session['name'] }}'s Avatar" class="avatar">
                    </div>


                    <div class="change-avatar-buttons">
                        <button id="change-avatar-button" class="change-avatar-button" title="Change the icon of yourself">😄 User Icon 😄</button>
                        <button id="change-agent-avatar-button" class="change-agent-avatar-button" title="Change the icon of your agent">🤖 Agent Icon 🤖</button>
                        <button class="composite-button interactive-button">
                            <div class="icon-container">
                                <span id="upload-file-button" class="icon" title="Upload file for agent to analyze">📁</span>
                            </div>
                            <div class="divider"></div>
                            <div class="icon-container">
                                <span id="show-files-button" class="icon" title="View files uploaded by you">🔍</span>
                            </div>
                            <div class="divider"></div>
                            <div class="icon-container">
                                <span id="delete-files-button" class="icon" title="Delete all files uploaded by you">❌</span>
                            </div>
                            <input type="file" id="file-input" multiple style="display: none;">
                        </button>

                        <div id="option-selection" class="option-selection" style="display: none;">
                            <button id="select-file-upload" class="option-button">File</button>
                            <button id="select-url-upload" class="option-button">URL</button>
                        </div>

                        <!-- Modal for URL input -->
                        <div id="urlModal" class="modal">
                            <div class="modal-content">
                                <span class="close_url">&times;</span>
                                <h2>Enter URL</h2>
                                <input type="text" id="url-input" placeholder="Enter URL" class="modal-input">
                                <button id="submit-url-button" class="modal-button">Submit URL</button>
                            </div>
                        </div>

                        <div id="file-modal" class="modal">
                            <div class="modal-content">
                                <span class="close">&times;</span>
                                <h2>Uploaded Files</h2>
                                <table id="file-table">
                                    <thead>
                                        <tr>
                                            <th>File Name</th>
                                            <th>Size</th>
                                            <th>Upload Date</th>
                                        </tr>
                                    </thead>
                                    <tbody id="file-table-body">
                                        <!-- File details will be added here dynamically -->
                                    </tbody>
                                </table>
                            </div>
                        </div>

                    </div>
                </div>


                <input type="file" id="avatar-file-input" style="display: none;" accept="image/*">
                <input type="file" id="agent-avatar-file-input" style="display: none;" accept="image/*">

                <div class="user-panel-container">
                    <button id="agent-admin-panel-button" class="agent-admin-panel-button" title="Admin panel for customizing your agent">Agent Admin Panel</button>
                </div>



                <h3>{{ session['name'] }}'s Friends</h3>
                <form method="post" action="/add_friend">
                    <input type="text" name="friend_name" placeholder="Add more friend ..." required>
                    <input type="submit" value="Add">
                </form>
                <ul>
                    {% for friend in friend_list %}
                    <li><a href="/chat?chat={{ friend[0] }}">{{ friend[0] }}</a></li>
                    {% endfor %}
                </ul>


                <div class="logout-container">
                    <a class="logout-link" href="/logout">Logout</a>
                </div>
            </div>
        </div>

        <div class="chat-history-container">
            <div class="chat-history" id="chat-history">
                <ul id="message-list">

                </ul>
            </div>
            <form class="message-input" id="message-form">
                <textarea name="message" id="message-input" placeholder="Type a message..." required></textarea>
                <input type="hidden" name="receiver" id="receiver" value="{{ friend_name }}">
                <input type="submit" value="Send">
            </form>
        </div>

        <script>
            // 使用 localStorage 初始化 feedbackState
            let feedbackState = JSON.parse(localStorage.getItem('feedbackState')) || {};

            let previousChat = '';
            // 存储滚动位置
            let friendListScrollPosition = 0;

            function renderMessage(message) {
                if (typeof message !== 'string') {
                    throw new Error('Expected a string');
                }
                return renderMarkdownWithTables(marked.parse(message));
            }

            let isAgentThinking = false;
            let thinkingAgentName = '';

            let isAgentAdminPanel = false;

            let lastMessageCount = 0;

            function fetchMessages() {
                const currentChat = document.getElementById('receiver').value;
                if (currentChat) {
                    if (isAgentAdminPanel) {
                        fetchMessagesAgentCultivate();
                    } else {
                        // 保存当前滚动位置
                        const friendList = document.querySelector('.friend-list ul');
                        friendListScrollPosition = friendList.scrollTop;

                        fetch(`/get_messages?chat=${currentChat}`)
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('Failed to fetch messages');
                                }
                                return response.json();
                            })
                            .then(data => {
                                const messageList = document.getElementById('message-list');
                                messageList.innerHTML = '';
                                data.messages.forEach(message => {
                                    const li = document.createElement('li');
                                    li.classList.add('message-item');


                                    let bubbleClass = 'received_bubble';
                                    let alignClass = 'left';
                                    if (message.sender === '{{ session["name"] }}') {
                                        bubbleClass = 'sent_bubble';
                                        alignClass = 'right';
                                    } else if (message.sender.endsWith("'s Agent")) {
                                        if (message.sender.startsWith('{{ session["name"] }}')) {
                                            bubbleClass = 'agent_sent_bubble';
                                            alignClass = 'right';
                                        } else {
                                            bubbleClass = 'agent_receive_bubble';
                                        }
                                    }


                                    const messageContainer = document.createElement('div');
                                    messageContainer.className = `chat-message ${alignClass}`;


                                    const senderInfo = document.createElement('div');
                                    senderInfo.className = `sender-info ${alignClass}`;


                                    const senderAvatar = document.createElement('img');
                                    senderAvatar.src = message.sender_profile_image_url;
                                    senderAvatar.alt = `${message.sender}'s avatar`;
                                    senderAvatar.classList.add('avatar');


                                    const senderName = document.createElement('div');
                                    senderName.classList.add('sender-name');
                                    senderName.textContent = message.sender;

                                    senderInfo.appendChild(senderAvatar);
                                    senderInfo.appendChild(senderName);


                                    const messageContent = document.createElement('div');
                                    messageContent.innerHTML = renderMessage(message.message);
                                    messageContent.classList.add('message-content');
                                    messageContent.classList.add(bubbleClass);


                                    if (alignClass === 'left') {
                                        messageContainer.appendChild(senderInfo);
                                        messageContainer.appendChild(messageContent);
                                    } else {
                                        messageContainer.appendChild(messageContent);
                                        messageContainer.appendChild(senderInfo);
                                    }

                                    li.appendChild(messageContainer);
                                    messageList.appendChild(li);

                                    if (message.raw_message.includes('Conclusion on Agents\' Communication')) {
                                        const feedbackLi = document.createElement('li');
                                        feedbackLi.className = 'feedback-container';
                                        
                                        const feedbackKey = `${message.sender}-${message.timestamp}`;
                                        const existingFeedback = feedbackState[feedbackKey];
                                        
                                        let feedbackContent;
                                        if (existingFeedback) {
                                            const feedbackClass = existingFeedback === 'good' ? 'feedback-good' : 'feedback-bad';
                                            const feedbackEmoji = existingFeedback === 'good' ? '👍' : '👎';
                                            feedbackContent = `
                                                <div class="feedback-box feedback-sent ${feedbackClass}">
                                                    <p><strong>Your feedback: ${feedbackEmoji}</strong></p>
                                                </div>
                                            `;
                                        } else {
                                            feedbackContent = `
                                                <div class="feedback-box">
                                                    <p><strong>Rate this agents' communication</strong></p>
                                                    <div class="feedback-buttons">
                                                        <button class="feedback-btn like-btn" data-feedback="good">👍</button>
                                                        <button class="feedback-btn dislike-btn" data-feedback="bad">👎</button>
                                                    </div>
                                                </div>
                                            `;
                                        }
                                        
                                        feedbackLi.innerHTML = feedbackContent;
                                        
                                        if (!existingFeedback) {
                                            const likeButton = feedbackLi.querySelector('.like-btn');
                                            const dislikeButton = feedbackLi.querySelector('.dislike-btn');
                                            
                                            [likeButton, dislikeButton].forEach(button => {
                                                button.addEventListener('click', function() {
                                                    const feedback = this.dataset.feedback;
                                                    sendFeedback(message.raw_message, message.communication_history, message.sender, message.receiver, feedback);
                                                    this.classList.add('clicked');
                                                    this.disabled = true;
                                                    
                                                    const otherButton = this === likeButton ? dislikeButton : likeButton;
                                                    otherButton.disabled = true;
                                                    
                                                    const feedbackBox = feedbackLi.querySelector('.feedback-box');
                                                    feedbackBox.classList.add('feedback-sent');
                                                    feedbackBox.classList.add(feedback === 'good' ? 'feedback-good' : 'feedback-bad');
                                                    
                                                    // Store the feedback state and update localStorage
                                                    feedbackState[feedbackKey] = feedback;
                                                    localStorage.setItem('feedbackState', JSON.stringify(feedbackState));

                                                    // Update the content to show the submitted feedback
                                                    feedbackBox.innerHTML = `<p><strong>Your feedback: ${feedback === 'good' ? '👍' : '👎'}</strong></p>`;
                                                });
                                            });
                                        }

                                        messageList.appendChild(feedbackLi);
                                    }
                                });

                                // Check if we need to show or keep the thinking message
                                if (isAgentThinking) {
                                    // 找到最后一条非结论消息
                                    let lastNonConclusionMessage = null;
                                    for (let i = data.messages.length - 1; i >= 0; i--) {
                                        if (!data.messages[i].message.includes("Conclusion on Agents\' Communication")) {
                                            lastNonConclusionMessage = data.messages[i];
                                            break;
                                        }
                                    }

                                    if (lastNonConclusionMessage) {
                                        console.log("Last non-conclusion message:", lastNonConclusionMessage);
                                        const otherAgent = lastNonConclusionMessage.sender === "{{ session['name'] }}'s Agent" 
                                            ? currentChat + "'s Agent" 
                                            : "{{ session['name'] }}'s Agent";
                                        console.log("Showing thinking message for:", otherAgent);
                                        showThinkingMessage(otherAgent);
                                    } else {
                                        console.log("No suitable message found to determine thinking agent");
                                        isAgentThinking = false; // 重置状态，因为没有合适的消息来决定谁在思考
                                    }
                                } else {
                                    console.log("Agent is not thinking");
                                }

                                if (currentChat !== previousChat) {
                                    document.getElementById('chat-history').scrollTop = document.getElementById('chat-history').scrollHeight;
                                }
                                previousChat = currentChat;
                                // 更新选中状态
                                updateSelectedFriend(currentChat);
                                // 恢复滚动位置
                                friendList.scrollTop = friendListScrollPosition;
                            })
                            .catch(error => console.error('Error fetching messages:', error));
                    }
                }
            }

            function sendFeedback(conclusion, communication_history, sender, receiver, feedback) {
                var conclusion = encodeURIComponent(conclusion);
                var communication_history = encodeURIComponent(communication_history);

                fetch('/send_feedback', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        conclusion: conclusion,
                        feedback: feedback,
                        sender: sender,
                        receiver: receiver,
                        communication_history: communication_history
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('Feedback sent successfully');
                        showToast('Feedback sent successfully', true);  // 添加成功提示
                    } else {
                        console.error('Error sending feedback:', data.error);
                        showToast('Error sending feedback', false);  // 添加错误提示
                    }
                })
                .catch(error => {
                    console.error('Error sending feedback:', error);
                    showToast('Error sending feedback', false);  // 添加错误提示
                });
            }

            fetchMessages();

            setInterval(fetchMessages, 3000);

            document.getElementById('message-form').addEventListener('submit', function (event) {
                event.preventDefault();
                sendMessage();
            });

            function sendMessage() {
                const formData = new FormData(document.getElementById('message-form'));
                const message = formData.get('message');
                const receiver = formData.get('receiver');
                const sender = "{{ session['name'] }}";
                formData.append('sender', sender);

                if (!message || !receiver) {
                    console.error('Error sending message: Receiver and message are required');
                    return;
                }

                if (sender + "'s Agent" == receiver) {
                    const origData = new FormData(document.getElementById('message-form'));
                    fetch('/execute_agent_cultivate?receiver=' + receiver + '&message=' + message + '&sender=' + sender)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to execute agent');
                            }
                            return response.json();
                        })
                        .then(data => {
                            origData.set('message', message);
                            origData.set('sender', sender);
                            origData.set('receiver', receiver);
                            origData.set('communication_history', 'None');
                            sendMessageNow(origData);

                            formData.set('message', data.agent_response);
                            formData.set('sender', sender + "'s Agent");
                            formData.set('communication_history', data.communication_history);
                            formData.set('receiver', sender);

                            sendMessageNow(formData);
                        })
                        .catch(error => console.error('Error executing agent:', error));
                }
                else if (message.startsWith('@')) {
                    isAgentThinking = true;
                    thinkingAgentName = sender + "'s Agent";
                    showThinkingMessage(thinkingAgentName);
                    fetch('/execute_agent?receiver=' + receiver + '&message=' + message + '&sender=' + sender)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to execute agent');
                            }
                            return response.json();
                        })
                        .then(data => {
                            formData.set('message', "**Conclusion on Agents' Communication:**\n" + data.agent_response);
                            formData.set('sender', sender + "'s Agent");
                            formData.set('communication_history', data.communication_history);

                            sendMessageNow(formData);
                            isAgentThinking = false;
                            thinkingAgentName = '';
                            fetchMessages(); // Fetch messages again to update the view
                        })
                        .catch(error => {
                            console.error('Error executing agent:', error);
                            isAgentThinking = false;
                            thinkingAgentName = '';
                            removeThinkingMessages();
                        });
                } else {
                    sendMessageNow(formData);
                }
            }

            function sendMessageNow(formData) {
                // Remove CSRF token from formData
                // const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                // formData.append('csrf_token', csrfToken);

                fetch('/send_message', {
                    method: 'POST',
                    body: formData,
                    // Remove CSRF token from headers
                    // headers: {
                    //     'X-CSRFToken': csrfToken
                    // }
                })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(`HTTP error! status: ${response.status}, message: ${text}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        console.log('Message sent successfully');
                        fetchMessages();
                        document.getElementById('message-input').value = '';
                    } else {
                        console.error('Error sending message:', data.error);
                        console.log('Full response:', data);
                    }
                })
                .catch(error => {
                    console.error('Error sending message:', error);
                    console.log('Error details:', {
                        name: error.name,
                        message: error.message,
                        stack: error.stack
                    });
                    console.log('FormData contents:');
                    for (let pair of formData.entries()) {
                        console.log(pair[0] + ': ' + pair[1]);
                    }
                });
            }

            function showThinkingMessage(agentName) {
                removeThinkingMessages(); // Remove any existing thinking messages
                const messageList = document.getElementById('message-list');
                const thinkingLi = document.createElement('li');
                thinkingLi.className = 'thinking-container';
                
                const thinkingBox = document.createElement('div');
                thinkingBox.className = 'thinking-box ' + (agentName.includes("{{ session['name'] }}") ? 'agent_sent_bubble' : 'agent_receive_bubble');
                
                const thinkingText = document.createElement('span');
                thinkingText.textContent = agentName + ' is thinking';
                
                const ellipsis = document.createElement('span');
                ellipsis.className = 'ellipsis';
                ellipsis.textContent = '...';
                
                thinkingBox.appendChild(thinkingText);
                thinkingBox.appendChild(ellipsis);
                
                thinkingLi.appendChild(thinkingBox);
                messageList.appendChild(thinkingLi);
                
                document.getElementById('chat-history').scrollTop = document.getElementById('chat-history').scrollHeight;

                // Animate ellipsis
                let dots = 0;
                const animateEllipsis = setInterval(() => {
                    dots = (dots + 1) % 4;
                    ellipsis.textContent = '.'.repeat(dots);
                }, 500);

                // Store the interval ID on the element to clear it later
                thinkingLi.dataset.animationInterval = animateEllipsis;
            }

            function removeThinkingMessages() {
                const messageList = document.getElementById('message-list');
                const thinkingMessages = messageList.querySelectorAll('.thinking-container');
                thinkingMessages.forEach(msg => {
                    // Clear the animation interval
                    clearInterval(parseInt(msg.dataset.animationInterval));
                    msg.remove();
                });
            }

            document.getElementById('message-input').addEventListener('keydown', function (event) {
                if (event.key === 'Enter' && !event.shiftKey) {
                    event.preventDefault();
                    sendMessage();
                } else if (event.key === 'Enter' && event.metaKey) {
                    this.value += '\n';
                }
            });


            document.getElementById('change-avatar-button').addEventListener('click', function () {
                document.getElementById('avatar-file-input').click();
            });

            document.getElementById('change-agent-avatar-button').addEventListener('click', function () {
                document.getElementById('agent-avatar-file-input').click();
            });

            document.getElementById('avatar-file-input').addEventListener('change', function () {
                uploadAvatar(this.files[0], '/upload_avatar');
            });

            document.getElementById('agent-avatar-file-input').addEventListener('change', function () {
                uploadAvatar(this.files[0], '/upload_agent_avatar');
            });

            function uploadAvatar(file, url) {
                const formData = new FormData();
                formData.append('avatar', file);

                fetch(url, {
                    method: 'POST',
                    body: formData
                }).finally(() => {
                    location.reload();
                });
            }

            // Elements
            const uploadButton = document.getElementById('upload-file-button');
            const optionSelection = document.getElementById('option-selection');
            const fileInput = document.getElementById('file-input');
            const selectFileUpload = document.getElementById('select-file-upload');
            const selectUrlUpload = document.getElementById('select-url-upload');
            const urlModal = document.getElementById('urlModal');
            const closeModal = document.getElementsByClassName('close_url')[0];
            const submitUrlButton = document.getElementById('submit-url-button');
            const urlInput = document.getElementById('url-input');

            // Show option selection
            uploadButton.addEventListener('click', function () {
                optionSelection.style.display = 'block';
            });

            // File upload option
            selectFileUpload.addEventListener('click', function () {
                fileInput.click();
                optionSelection.style.display = 'none';
            });

            // URL upload option
            selectUrlUpload.addEventListener('click', function () {
                urlModal.style.display = 'block';
                optionSelection.style.display = 'none';
            });

            // Close modal
            closeModal.onclick = function () {
                urlModal.style.display = 'none';
            }

            // Close modal when clicking outside of it
            window.onclick = function (event) {
                if (event.target == urlModal) {
                    urlModal.style.display = 'none';
                }
            }

            // Handle file input change
            fileInput.addEventListener('change', function () {
                uploadFiles(this.files, '/upload_file');
            });

            // Handle URL submission
            submitUrlButton.addEventListener('click', function () {
                const url = urlInput.value;
                if (url) {
                    uploadURL(url, '/upload_file');
                    urlModal.style.display = 'none';
                } else {
                    showToast('URL is required', false);
                }
            });

            function uploadFiles(files, url) {
                const formData = new FormData();
                for (let i = 0; i < files.length; i++) {
                    formData.append('files[]', files[i]);
                }

                fetch(url, {
                    method: 'POST',
                    body: formData
                }).then(response => {
                    if (response.ok) {
                        showToast('Files uploaded successfully', true);
                    } else {
                        showToast('File upload failed', false);
                    }
                }).catch(error => {
                    console.error('Error:', error);
                    showToast('File upload failed', false);
                });
            }

            function uploadURL(url, targetUrl) {
                fetch(targetUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ url: url })
                }).then(response => {
                    if (response.ok) {
                        showToast('URL content uploaded successfully', true);
                    } else {
                        showToast('URL content upload failed', false);
                    }
                }).catch(error => {
                    console.error('Error:', error);
                    showToast('URL content upload failed', false);
                });
            }


            function showToast(message, success) {
                Toastify({
                    text: message,
                    duration: 2000,
                    close: true,
                    gravity: "top",
                    position: "center",
                    backgroundColor: success ? "#06C05F" : "gray",
                    stopOnFocus: true
                }).showToast();
            }

            // Function to fetch and display uploaded files
            document.getElementById('show-files-button').addEventListener('click', function () {
                fetch('/get_uploaded_files')
                    .then(response => response.json())
                    .then(data => {
                        populateFileTable(data);
                        document.getElementById('file-modal').style.display = 'block';
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
            });

            // Close modal when close button or outside modal is clicked
            var modal = document.getElementById('file-modal');
            var span = document.getElementsByClassName('close')[0];
            span.onclick = function () {
                modal.style.display = 'none';
            };
            window.onclick = function (event) {
                if (event.target == modal) {
                    modal.style.display = 'none';
                }
            };

            // Function to populate file table with data
            function populateFileTable(files) {
                var tableBody = document.getElementById('file-table-body');
                tableBody.innerHTML = ''; // Clear existing rows

                files.forEach(file => {
                    var row = tableBody.insertRow();
                    row.insertCell(0).textContent = file.name;
                    row.insertCell(1).textContent = formatBytes(file.size);
                    row.insertCell(2).textContent = formatDate(file.upload_date);
                });
            }

            // Helper function to format file size
            function formatBytes(bytes) {
                if (bytes === 0) return '0 Bytes';
                var k = 1024;
                var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                var i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }

            // Helper function to format date with seconds precision
            function formatDate(dateString) {
                var options = { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
                var date = new Date(dateString);
                return date.toLocaleDateString('en-US', options);
            }

            document.getElementById('delete-files-button').addEventListener('click', function () {
                if (confirm('Are you sure you want to delete all files? This action cannot be undone.')) {
                    deleteAllFiles();
                }
            });

            function deleteAllFiles() {
                fetch('/delete_all_files', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.message) {
                            showToast(data.message);
                        } else if (data.error) {
                            showToast(data.error);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        showToast('An error occurred while deleting files.');
                    });
            }

            document.getElementById('agent-admin-panel-button').addEventListener('click', function () {
                openAgentChat();
            });

            function openAgentChat() {
                const receiver = "{{ session['name'] }}'s Agent";
                document.getElementById('receiver').value = receiver;
                isAgentAdminPanel = true;
                fetchMessagesAgentCultivate();
            }

            function fetchMessagesAgentCultivate() {
                const currentChat = document.getElementById('receiver').value;
                if (currentChat && isAgentAdminPanel) {
                    fetch(`/get_messages?chat=${currentChat}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Failed to fetch messages');
                            }
                            return response.json();
                        })
                        .then(data => {
                            const messageList = document.getElementById('message-list');
                            const chatHistory = document.getElementById('chat-history');
                            const wasScrolledToBottom = chatHistory.scrollHeight - chatHistory.clientHeight <= chatHistory.scrollTop + 1;
                            
                            messageList.innerHTML = '';
                            
                            // 总是显示介绍消息
                            const introMessage = document.createElement('div');
                            introMessage.className = 'intro-message';
                            introMessage.innerHTML = `
                                <h2>Welcome to the Agent Admin Panel</h2>
                                <p>This is where you can customize your personal LLM agent. All the customization is done by simply chatting with your agent. Here are some things you can do:</p>
                                <ul>
                                    <li>Ask your agent to return in certain format.</li>
                                    <li>Ask your agent to role play in certain scenario.</li>
                                    <li>Ask your agent to behave in certain way.</li>
                                    <li>Input @ to automatically improve your agent's system profile using feedback data from your conversation with your friend.</li>
                                </ul>
                                <p>Start by sending a message to your agent below!</p>
                            `;
                            messageList.appendChild(introMessage);

                            // 显示现有的消息
                            data.messages.forEach(message => {
                                const li = document.createElement('li');
                                li.classList.add('message-item');

                                let bubbleClass = 'received_bubble';
                                let alignClass = 'left';
                                if (message.sender === '{{ session["name"] }}') {
                                    bubbleClass = 'sent_bubble';
                                    alignClass = 'right';
                                } else if (message.sender === '{{ session["name"] }}\'s Agent') {
                                    bubbleClass = 'agent_sent_bubble';
                                    alignClass = 'right';
                                }

                                const messageContainer = document.createElement('div');
                                messageContainer.className = `chat-message ${alignClass}`;

                                const senderInfo = document.createElement('div');
                                senderInfo.className = `sender-info ${alignClass}`;

                                const senderAvatar = document.createElement('img');
                                senderAvatar.src = message.sender_profile_image_url;
                                senderAvatar.alt = `${message.sender}'s avatar`;
                                senderAvatar.classList.add('avatar');

                                const senderName = document.createElement('div');
                                senderName.classList.add('sender-name');
                                senderName.textContent = message.sender;

                                senderInfo.appendChild(senderAvatar);
                                senderInfo.appendChild(senderName);

                                const messageContent = document.createElement('div');
                                messageContent.innerHTML = renderMessage(message.message);
                                messageContent.classList.add('message-content');
                                messageContent.classList.add(bubbleClass);

                                if (alignClass === 'left') {
                                    messageContainer.appendChild(senderInfo);
                                    messageContainer.appendChild(messageContent);
                                } else {
                                    messageContainer.appendChild(messageContent);
                                    messageContainer.appendChild(senderInfo);
                                }

                                li.appendChild(messageContainer);
                                messageList.appendChild(li);
                            });

                            // 只在新消息到达或者之前在底部时才滚动到底部
                            if (data.messages.length > lastMessageCount || wasScrolledToBottom) {
                                chatHistory.scrollTop = chatHistory.scrollHeight;
                            }
                            
                            lastMessageCount = data.messages.length;
                        })
                        .catch(error => console.error('Error fetching messages:', error));
                }
            }

            // 添加新函数来更新选中状态
            function updateSelectedFriend(currentChat) {
                const friendItems = document.querySelectorAll('.friend-list li');
                friendItems.forEach(item => {
                    if (item.textContent.trim() === currentChat) {
                        item.classList.add('selected');
                    } else {
                        item.classList.remove('selected');
                    }
                });
            }

            // 修改现有的事件监听器，为好友列表项添加点击事件
            document.addEventListener('DOMContentLoaded', function() {
                const friendItems = document.querySelectorAll('.friend-list li a');
                friendItems.forEach(item => {
                    item.addEventListener('click', function(e) {
                        e.preventDefault();
                        const friendName = this.textContent.trim();
                        document.getElementById('receiver').value = friendName;
                        isAgentAdminPanel = false;
                        fetchMessages();
                    });
                });
            });

            function renderMarkdownWithTables(text) {
                const tableRegex = /\|(.+)\n\|(?:[-:]+[-| :]*)\n((?:\|.+\n?)+)/g;
                text = text.replace(tableRegex, (match) => {
                    const rows = match.trim().split('\n');
                    const headers = rows[0].split('|').filter(cell => cell.trim() !== '');
                    const alignments = rows[1].split('|').filter(cell => cell.trim() !== '').map(cell => {
                        if (cell.startsWith(':') && cell.endsWith(':')) return 'center';
                        if (cell.endsWith(':')) return 'right';
                        return 'left';
                    });
                    const body = rows.slice(2).map(row => row.split('|').filter(cell => cell.trim() !== ''));

                    let tableHtml = '<table><thead><tr>';
                    headers.forEach((header, i) => {
                        tableHtml += `<th align="${alignments[i] || 'left'}">${header.trim()}</th>`;
                    });
                    tableHtml += '</tr></thead><tbody>';
                    body.forEach(row => {
                        tableHtml += '<tr>';
                        for (let i = 0; i < headers.length; i++) {
                            tableHtml += `<td align="${alignments[i] || 'left'}">${(row[i] || '').trim()}</td>`;
                        }
                        tableHtml += '</tr>';
                    });
                    tableHtml += '</tbody></table>';
                    return tableHtml;
                });

                return marked.parse(text);
            }

            // Add this new function to initialize and start the guide
            function startGuide() {
                const steps = [
                    {
                        element: document.querySelector('.friend-list form'),
                        intro: "Add friends: Type a username in this box and click 'Add' to connect with other users.",
                        position: 'right'
                    },
                    {
                        element: document.querySelector('.agent-admin-panel-button'),
                        intro: "Cultivate your agent: Click here to access the Agent Admin Panel, chat with your agent to teach them how to behave when collaborating with others.",
                        position: 'left'
                    },
                    {
                        element: document.querySelector('.change-avatar-buttons'),
                        intro: "Customize your appearance: Click 'User Icon' to change your profile picture, and 'Agent Icon' to change your agent's avatar.",
                        position: 'left'
                    },
                    {
                        element: document.querySelector('.composite-button'),
                        intro: "Use RAG (Retrieval-Augmented Generation): Upload documents or provide URLs here. Your agent will use this information to enhance its collaboration with others.",
                        position: 'left'
                    },
                    {
                        element: document.querySelector('.chat-history'),
                        intro: "Chat: This is where your conversations appear. Just like any other IM Apps, type and chat here with your friends.",
                        position: 'left'
                    },
                    {
                        element: document.querySelector('.message-input'),
                        intro: "Invoke your agent: Type '@' followed by your message, which will turn your message into task prompt to call your agent. Your agent will then work with your friend's agent to complete the task.",
                        position: 'top'
                    }
                ];

                introJs().setOptions({
                    steps: steps,
                    showStepNumbers: false,
                    exitOnOverlayClick: false,
                    exitOnEsc: false,
                    doneLabel: "Got it!"
                }).start().oncomplete(function() {
                    // Mark the guide as seen
                    fetch('/mark_guide_seen', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRFToken': '{{ csrf_token }}'  // Remove the parentheses
                        }
                    }).then(response => response.json())
                      .then(data => console.log(data))
                      .catch(error => console.error('Error:', error));
                });
            }

            // Check if the user has seen the guide
            {% if not session.get('guide_seen', False) %}
                window.addEventListener('load', startGuide);
            {% endif %}

        </script>
    </div>
</body>

</html>